package com.swm.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.swm.mapper.StockMapper;
import com.swm.pojo.Stock;
import org.apache.ibatis.session.SqlSession;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 师文明
 * @data 2024/12/23 下午3:11
 **/
public class getStockDayData32 {

    public static int allup;
    public static double allupnum;
    static SqlSession sqlSession = SqlSessionUtil.openSession();
    static StockMapper mapper = sqlSession.getMapper(StockMapper.class);

    public static List<Stock> getStcokList() {
        List<Stock> stocks = mapper.selectAllStock();
        JSONObject jsonObject = new JSONObject();

        for (Stock stock : stocks) {
            String code = stock.getCode();
            int type = stock.getType();
            jsonObject.put(code, type);

        }
        return stocks;
    }

    public static void main(String[] args) throws Exception {

        ExecutorService executorService = Executors.newFixedThreadPool(50);
        //获取所有股票列表
        List<Stock> stcokList = getStcokList();
        for (Stock stock : stcokList) {
            executorService.execute(() -> {
                try {
                    getData(stock.getCode(), stock.getType());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }

        Thread.sleep(50000);
        double v = 0;
        if (allup != 0) {
            v = allupnum / allup;
        }

        System.out.println(("平均涨幅：" + v));//+"\r\n"));
        // 关闭线程池，以优雅的方式

        executorService.shutdown();

        // 关闭线程池，以优雅的方式
        // 关闭线程池，以优雅的方式
    }

    public static void getData(String code, int type) throws Exception {
        String data = getWebData(code, type);
        if (data == null) {
            return;
        }

        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get("data") != null) {
            JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("data").toString());
            String name = jsonObject1.get("name").toString();
            JSONArray klines = JSONArray.parse(jsonObject1.get("klines").toString());
            if (klines.size() > 250) {
                for (int i = 2; i < 100; i++) {

                    //最近120天内成交量集合
                    List<Double> numbers = new ArrayList<>();
                    //最近120天内收盘价集合
                    List<Double> prices = new ArrayList<>();
                    double v1 = Double.parseDouble(klines.get(klines.size() - i).toString().split(",")[5]);
                    double p1 = Double.parseDouble(klines.get(klines.size() - i).toString().split(",")[2]);
                    for (int j = 0; j < 120; j++) {
                        //成交量
                        double v2 = Double.parseDouble(klines.get(klines.size() - (i + j)).toString().split(",")[5]);
                        numbers.add(v2);
                        //收盘价
                        double p2 = Double.parseDouble(klines.get(klines.size() - (i + j)).toString().split(",")[2]);
                        prices.add(p2);
                    }
                    // 使用List的sort()方法和Lambda表达式进行排序
                    numbers.sort(Double::compare);
                    // 使用List的sort()方法和Lambda表达式进行排序
                    prices.sort(Double::compare);


                    boolean moneyUp = getMoneyUp(klines, i);
                    boolean amplitude = getAmplitude(klines, i);
                    double v0 = Double.parseDouble(klines.get(klines.size() - i).toString().split(",")[8]);

                    if (v0 < 9.8 && v0 > 0 && moneyUp && amplitude && v1 > numbers.get(109) && p1 < prices.get(50)) {

                        double v = Double.parseDouble(klines.get(klines.size() - i + 1).toString().split(",")[8]);
                        allupnum += v;
                        allup++;
                        System.out.println(name + ":" + klines.get(klines.size() - i).toString().split(",")[0] + "次日涨幅：" + v);
                    }
                }

            }
        }
    }

    public static String getWebData(String code, int type) {
        String data = null;
        try {
            // 连接到新浪财经接口
            String url = "https://push2his.eastmoney.com/api/qt/stock/kline/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f116,f117&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&beg=0&end=20500101&rtntype=6&secid=" + type + "." + code + "&klt=101&fqt=1";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Cookie", "qgqp_b_id=488de58836c5f30c189b9ad4c700b9f5; st_si=04137509447995; websitepoptg_api_time=1734056942833; st_asi=delete; HAList=ty-1-603999-%u8BFB%u8005%u4F20%u5A92%2Cty-0-002888-%u60E0%u5A01%u79D1%u6280%2Cty-0-002269-%u7F8E%u90A6%u670D%u9970%2Cty-0-000813-%u5FB7%u5C55%u5065%u5EB7%2Cty-0-002045-%u56FD%u5149%u7535%u5668%2Cty-0-300059-%u4E1C%u65B9%u8D22%u5BCC%2Cty-1-688605-N%u5148%u950B%2Cty-1-000001-%u4E0A%u8BC1%u6307%u6570; st_pvi=62081555482493; st_sp=2024-12-11%2010%3A26%3A42; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=60; st_psi=20241213164756225-113200301201-5528754653");
            // 设置连接超时时间为 10 秒
            con.setConnectTimeout(10000);
            // 设置读取超时时间为 10 秒
            con.setReadTimeout(10000);
            // 从数据源获取实时股票数据
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            con.disconnect();
            data = response.toString();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            //e.printStackTrace();
        }

        return data;
    }

    public static boolean getMoneyUp(JSONArray klines, int startDay) {
        //往前推的天数
        int bedays = 2;
        //从哪天开始 1就是今天
        //int startDay=1;
        boolean re = false;
        double multiple = 5;

        //今日成交额
        double v0 = Double.parseDouble(klines.get(klines.size() - startDay).toString().split(",")[5]);
        for (int j = 1; j < bedays; j++) {
            //j天前成交额
            double v1 = Double.parseDouble(klines.get(klines.size() - (startDay + j)).toString().split(",")[5]);
            if (v0 / v1 > multiple) {
                re = true;
                break;
            }
        }

        return re;
    }


    //获取最近成交额稳定价格稳定是否存在
    public static boolean getAmplitude(JSONArray klines, int startDay) {

        //最近几天内
        int days = 5;
        //往前推的天数
        int bedays = 21;

        //从哪天开始 1就是今天
        // int startDay=1;

        double max = 0;
        double min = 1000000000;
        double average = 0;
        double total = 0;

        double maxprice = 0;
        double minprice = 10000;

        //
        boolean priceflag = false;
        //十天振幅
        for (int num = startDay; num < days + startDay; num++) {
            double price0 = Double.parseDouble(klines.get(klines.size() - num).toString().split(",")[2]);
            for (int i = num; i < (num + bedays); i++) {
                String[] split = klines.get(klines.size() - i).toString().split(",");
                double price = Double.parseDouble(split[2]);
                maxprice = Math.max(price, maxprice);
                minprice = Math.min(price, minprice);
                minprice = price < minprice ? price : min;
            }
            double priceDiff = (maxprice - minprice) / price0;
            if (priceDiff < 0.1) {
                priceflag = true;
            }
        }

        boolean moneyflag = false;
        for (int num = startDay; num < days + startDay; num++) {
            for (int i = num; i < (num + bedays); i++) {
                String[] split = klines.get(klines.size() - i).toString().split(",");
                double money = Double.parseDouble(split[5]);
                max = Math.max(money, max);
                min = Math.min(money, min);
                total += money;
            }
            average = total / bedays;
            //十天内成交量振幅
            double v3 = (max - min) / average;
            if (v3 < 1) {
                moneyflag = true;
            }
        }
        return priceflag && moneyflag;
    }
}

